﻿using Common;
using FluentValidation.Results;
using HslCommunication.Core;
using PLC.Domain.Dto;
using PLC.Domain.Entity;
using PLC.Domain.Enum;
using PLC.Domain.Models;
using PLC.Domain.Service.IRepository;

namespace PLC.Domain.ScheduledTasks.Strategy.Read;
/// <summary>
/// 读取生产的数据
/// </summary>
public class ReadProductionData : BaseRead
{
    private readonly IPLCRepository _plcRepository;

    public ReadProductionData(IPLCRepository plcRepository)
    {
        _plcRepository = plcRepository ?? throw new ArgumentNullException(nameof(plcRepository));
    }
    public override EnumReadGroup ReadGroup { get; protected set; } =EnumReadGroup.生产数据;
   
    public override void Read(IReadWriteNet readWriteNet, PLCConfig plcConfig, List<DtoDataConfig> readConfigList,PLCReadModel plcReadModel)
    {
        if (readConfigList.Count == 0)
        {
            return;
        }
        // 批次id表明是同一个批次读取上来的数据
        var productionData = new DtoProductionData()
        {
            DeviceType = plcConfig.DeviceConfig.DeviceType
        };
        var dataList = new List<PLCDataModel>();
        foreach (var config in readConfigList)
        {
            var data = _plcRepository.ReadData(readWriteNet, config.Register, (EnumDataType)config.DataType,
                (EnumDataEncoding)(config.Encoding ?? 0), config.DataLength);
            if (config.CodeType==null)
            {
                continue;
            }
            else if ( config.CodeType==(int)EnumProductionDataType.上端板码)
            {
                productionData.UpperEndPlateCode = data;
                continue;
            }else if (config.CodeType == (int)EnumProductionDataType.下端板码)
            {
                productionData.LowerEndPlateCode=data;
                continue;
            }else if (config.CodeType == (int)EnumProductionDataType.任务编号)
            {
                productionData.TaskCode=data;
                continue;
            }else if (config.CodeType == (int)EnumProductionDataType.OK和NG)
            {
                productionData.Result = data.ToInt32();
                continue;
            }else if (config.CodeType==(int)EnumProductionDataType.数据)
            {
                var description = GetValueDescription(data, config);
                var dataModel = new PLCDataModel()
                {
                    Register = config.Register,
                    DataType = config.DataType,
                    Description = description,
                    Value = data
                };
                dataList.Add(dataModel);
            }
        }

        productionData.Data =dataList.Count==0?"": JsonHelper.SerializeObject(dataList);
        plcReadModel.DtoProductionData = productionData;
    }
}